const { app, BrowserWindow, ipcMain, dialog, shell, Menu, Tray } = require("electron");
const path = require("node:path");
const createClient = require('webdav').createClient;
const keytar = require('keytar');
const { exec } = require('child_process');
const fs = require('fs');
const { autoUpdater } = require('electron-updater');
const log = require('electron-log');
const SERVICE_NAME = 'eaglesoft-webdav-client';
const VIRTUAL_ROOT = path.join(app.getPath('userData'), 'virtual_z_drive');

let mainWindow;
let webdavClient = null;
let _serverUrl = null;
let _username = null;
let _password = null;
let _userInfo = {};
let _authList = [];

let isQuitting = false;
let tray;

if (require('electron-squirrel-startup')) {
  app.quit();
}

async function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1024, //自己需要的宽高
    height: 960,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      nodeIntegration: false,
      contextIsolation: true,
      webSecurity: false,
      sandbox: true
    },
  });

  await mainWindow.loadURL(app.isPackaged ? "http://60.217.68.78:8110/posseidon/" : "http://172.16.28.74:9024/posseidon/");
  // 初始化自动更新
  initAutoUpdater();
  // mainWindow.loadURL("http://192.168.110.75:8082/");
  if (!app.isPackaged) {
    mainWindow.webContents.openDevTools(); // 打开调试工具
  }
  Menu.setApplicationMenu(null);

  mainWindow.on('close', (event) => {
    if (!isQuitting) {
      event.preventDefault();
      mainWindow.hide();
      return;
    }
    return cleanupBeforeQuit();
  });
  setupTray();
}

// 添加清理函数
async function cleanupBeforeQuit() {
  await unmountDrive('Z:');
}
// 修改托盘菜单
function setupTray() {
  const iconPath = path.join(__dirname, 'logo.png');
  tray = new Tray(iconPath);
  tray.setToolTip('网盘在此');
  
  const contextMenu = Menu.buildFromTemplate([
    { 
      label: '显示应用', 
      click: () => {
        mainWindow.show();
      }
    },
    { 
      label: '退出应用', 
      click: async () => {
        isQuitting = true;
        await cleanupBeforeQuit();
        app.quit();
      }
    }
  ]);
  
  tray.setContextMenu(contextMenu);
  tray.on('click', () => {
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
  });
}

// 初始化 WebDAV 客户端
async function initWebDAVClient(username, password, serverUrl) {
  _serverUrl = serverUrl;
  _username = username;
  _password = password;
  console.log('初始化 WebDAV 客户端:', serverUrl, username);
  webdavClient = createClient(serverUrl, {
    username,
    password,
    authType: 'digest',
    proxy: false,
    headers: { 'User-Agent': 'Electron-WebDAV-Client' }
  });

  try {
    const contents = await webdavClient.getDirectoryContents('/', {
      details: true,
      timeout: 30000
    });
    const hasPersonalSpace = contents.data.some(item => 
      item.type === 'directory' && item.basename === `${_userInfo.xm}个人空间_${_userInfo.bh}` && item.props?.bh === _userInfo.bh
    );
    if (!hasPersonalSpace) {
      await createPersonalFolderWithProps();
    }
    console.log('WebDAV 连接成功，根目录文件数:', contents.data.length);
    return true;
  } catch (error) {
    const errorMsg = 
      error.response?.status === 401 ? '认证失败，请检查用户名/密码' :
      error.response?.status === 404 ? '服务器地址无效' :
      error.message;
    
    console.error('WebDAV 连接失败:', errorMsg);
    if (error.response?.status === 404) {
      dialog.showMessageBox(mainWindow, {
        type: 'warning',
        title: '提示',
        message: '该账号尚无配置文件路径，请点击一键关联文件进行同步',
        buttons: ['确定']
      });
    }
    throw new Error(errorMsg);
  }
}

async function createPersonalFolderWithProps() {
  const folderPath = `${_userInfo.xm}个人空间_${_userInfo.bh}`;
  await webdavClient.createDirectory(`/${folderPath}/`);
  const xmlBody = `<?xml version="1.0" encoding="UTF-8"?>
  <D:propertyupdate xmlns:D="DAV:">
    <D:set>
      <D:prop>
        <myprops:bh xmlns:myprops="http://example.com">${_userInfo.bh}</myprops:bh>
      </D:prop>
    </D:set>
  </D:propertyupdate>`;
  await webdavClient.customRequest(`/${folderPath}/`, {
    method: 'PROPPATCH',
    headers: {
      'Content-Type': 'application/xml; charset=utf-8'
    },
    data: xmlBody
  });
}

// 虚拟文件系统核心逻辑
async function setupVirtualDrive() {
  const userDir = path.join(VIRTUAL_ROOT, `${_userInfo.xm}-${_userInfo.bh}`);
  try {
  // 串行复制目录（避免服务器压力）
  await copyDirectoryWithCheck('/', userDir, true).catch(e => console.error('目录复制静默失败:', e.message));
  // 3. 映射到Z盘 (Windows)
  if (process.platform === 'win32') {
    await unmountDrive('Z:');
    const resetAndSetReadOnly = async (dirPath) => {
      const steps = [
        `icacls "${dirPath}" /reset`,          // 清除所有现有权限
        `icacls "${dirPath}" /grant *S-1-1-0:R` // 仅授予"所有人"读取权限(S-1-1-0是Everyone的SID)
      ];

      for (const cmd of steps) {
        const success = await new Promise(r => {
          exec(cmd, (err) => r(!err));
        });
        if (!success) return false;
      }
      return true;
    };
    await resetAndSetReadOnly(userDir);
    try {
      await exec(`subst Z: "${path.normalize(userDir)}"`, { shell: 'cmd.exe' });
      console.log(`成功映射 Z: 驱动器`);
      const { response } = await dialog.showMessageBox(mainWindow, {
          type: 'warning',
          title: '提示',
          message: '加载文件完成，是否隐藏至托盘？',
          buttons: ['是', '否']
        });
        
        if (response === 0) {
          mainWindow.hide();
        }
    } catch (error) {
      console.error('Z盘映射失败:', err);
    }
  }
  } catch (err) {
    console.error('虚拟驱动器设置失败:', err);
    throw err;
  }
}

/**
 * 安全复制单个文件（带权限验证和错误处理）
 * @param {string} remotePath WebDAV服务器文件路径（如 '/体系文件/船舶报告.html'）
 * @param {string} localRoot 本地虚拟文件系统根目录
 * @param {string} username 当前操作用户
 * @returns {Promise<void>}
 */
async function copyFileWithCheck(remotePath, localRoot) {
  const localPath = path.join(localRoot, remotePath.replace(/^\//, ''));
  
  try {
    // 2. 创建父目录（递归）
    fs.mkdirSync(path.dirname(localPath), { 
      recursive: true,
      mode: 0o755 // 确保目录有正确权限
    });

    // 3. 下载文件内容（带重试机制）
    const MAX_RETRIES = 3;
    const BASE_DELAY = 1000;
    let lastError;

    for (let i = 0; i < MAX_RETRIES; i++) {
      try {
        // 3.1 获取文件内容
        const arrayBuffer = await webdavClient.getFileContents(remotePath, {
          headers: {
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive'
          },
          timeout: 30000 // 30秒超时
        });

        // 3.2 写入本地文件（原子操作）
        const tmpPath = `${localPath}.${Date.now()}.tmp`;
        fs.writeFileSync(tmpPath, Buffer.from(arrayBuffer));
        fs.renameSync(tmpPath, localPath); // 原子替换
        
        // console.log(`[成功] 复制 ${remotePath} -> ${localPath}`);
        return;

      } catch (err) {
        if (i === MAX_RETRIES - 1) throw err;
        const delay = BASE_DELAY * Math.pow(2, i);
        console.warn(`[重试 ${i+1}/${MAX_RETRIES}] 文件 ${remotePath} 下载失败:`, err.message);
        await new Promise(r => setTimeout(r, delay + Math.random() * 1000));
      }
    }

    throw lastError;

  } catch (error) {
    // 4. 错误清理
    if (fs.existsSync(localPath)) {
      fs.unlinkSync(localPath).catch(() => {});
    }
    console.error(`[最终失败] 文件 ${remotePath} 复制失败:`, error.message);
    throw new Error(`FILE_COPY_FAILED: ${remotePath}`);
  }
}


/**
 * 安全复制目录及其内容（递归+权限过滤）
 * @param {string} remoteDir WebDAV服务器目录路径（如 '/体系文件/'）
 * @param {string} localRoot 本地虚拟文件系统根目录
 * @param {boolean} isMain 是否首页，拿到权限判断是非体系还是体系
 * @param {boolean} qxbs 非体系/体系的权限
 * @returns {Promise<void>}
 */
// 新增并发控制函数
async function parallelWithLimit(tasks, limit = 5) {
  const results = [];
  const executing = new Set();
  
  for (const task of tasks) {
    const p = Promise.resolve().then(() => task());
    executing.add(p);
    results.push(p);
    
    p.then(() => executing.delete(p));
    
    if (executing.size >= limit) {
      await Promise.race(executing);
    }
  }
  
  return Promise.all(results);
}

async function copyDirectoryWithCheck(remoteDir, localRoot, isMain = false, PQxbs = null, PqxbsB = null) {
  const localDir = path.join(localRoot, remoteDir.replace(/^\//, ''));
  try {
    // 1. 清空目标目录（如果存在）
    if (await fs.existsSync(localDir)) {
      await fs.rmSync(localDir, { recursive: true, force: true });
    }
    // 2. 创建本地目录
    await fs.mkdirSync(localDir, {
      recursive: true,
      mode: 0o755
    });

    // 3. 获取远程目录内容
    const contents = await webdavClient.getDirectoryContents(remoteDir, {
      details: true,
      timeout: 30000
    });

    // 4. 并行处理目录内容
    await parallelWithLimit(contents.data.map(item => async () => {
      const itemRemotePath = `${remoteDir}${item.basename}${item.type === 'directory' ? '/' : ''}`;
      let qxbs = PQxbs;
      let qxbsB = PqxbsB;
      try {
        if (item.type === 'directory') {
          if (item.props.qx) {
            const regex = /\[([^,]+),\s*([^\]]+)\]/; // 匹配方括号内的内容
            const result = regex.exec(item.props.qx).slice(1).map(res => res.trim());
            qxbsB = result[0];
            qxbs = result[1];
          }
          if (isMain && item.basename === `${_userInfo.xm}个人空间_${_userInfo.bh}`) {
            if (item.props?.bh === _userInfo.bh) {
              await copyDirectoryWithCheck(itemRemotePath, localRoot, false, qxbs, qxbsB);
            }
          } else {
            if (item.basename.includes('个人空间') && item.props.bh !== _userInfo.bh) {
              console.error(item.basename, '不是该人个人空间');
            } else {
              await copyDirectoryWithCheck(itemRemotePath, localRoot, false, qxbs, qxbsB);
            }
          }
        } else {
          // 判断文件权限 select和select_3和select_file 全部 select_2 根据bmList select_1 根据yh
          let hasQx = false;
          if (qxbs === null) {
            hasQx = true;
          } else {
            const qxbsList = ['select', 'select_1', 'select_2', 'select_3'];
            const authList = _authList.filter(item => item.menu === qxbsB);
            if (authList.length) {
              // const matched = authList.filter(item => qxbsList.includes(item.qxbs)).map(item => item.qxbs);
              // const qxbsT = [...new Set(matched)].join(', ');
              let qxbsT = null;
              if (qxbs === 'select') {
                const matchedItem = authList.find(item => qxbsList.includes(item.qxbs));
                qxbsT = matchedItem ? matchedItem.qxbs : null;
              } else {
                const hasExactMatch = authList.some(item => item.qxbs === qxbs);
                qxbsT = hasExactMatch ? qxbs : null;
              }
              if (qxbsT) {
                if (qxbsT === 'select_2') {
                  hasQx = getHasQx(item.props, 2);
                } else if (qxbsT === 'select_1') {
                  hasQx = getHasQx(item.props, 1);
                } else {
                  hasQx = true;
                }
                // 船舶证书的话select_2全部，select_1部门
                if (item.filename.includes('/证书/船舶证书/')) {
                  if (qxbsT === 'select_2') {
                    hasQx = true;
                  } else if (qxbsT === 'select_1') {
                    hasQx = getHasQx(item.props, 2);
                  } else {
                    hasQx = false;
                  }
                }
              } else {
                hasQx = false;
              }
            }
          }
          if (hasQx) {
            await copyFileWithCheck(itemRemotePath, localRoot);
          }
        }
      } catch (error) {
        console.error(`处理 ${item.basename} 失败:`, error.message);
        // 可在此记录失败文件供后续重试
      }
    }), 5); // 并发数限制
  } catch (error) {
    // 5. 错误清理
    if (fs.existsSync(localDir)) {
      fs.rmSync(localDir, { recursive: true, force: true }).catch(() => {});
    }
    console.error(`[目录失败] ${remoteDir} 复制失败:`, error.message);
    throw new Error(`DIR_COPY_FAILED: ${remoteDir}`);
  }
}

// type 1 全部 2部门 3个人
function getHasQx(props, type) {
  switch (type) {
    case 1:
      return true;
    case 2:
      const bmList = JSON.parse(props.bmList);
      if (bmList.includes(_userInfo.bm)) {
        return true;
      }
      return false;
    case 3:
      const yhList = JSON.parse(props.yh);
      if (yhList.includes(_userInfo.bh)) {
        return true;
      }
      return false;
    default:
      return false;
  }
}

// IPC 处理
ipcMain.handle('webdav-connect', async (event, { username, password, serverUrl, userInfo, authList }) => {
  console.log('尝试连接 WebDAV 服务器:', serverUrl, username);
  _userInfo = userInfo;
  _authList = authList;
  await keytar.setPassword(SERVICE_NAME, username, password);
  const connected = await initWebDAVClient(username, password, serverUrl);
  if (connected) {
    event.sender.send('connect-success', {});
    await setupVirtualDrive(username);
  }
  return connected;
});

ipcMain.handle('webdav-disconnect', async (event, username) => {
  await keytar.deletePassword(SERVICE_NAME, username);
  webdavClient = null;
  return true;
});

ipcMain.handle('webdav-list', async (event, path = '/') => {
  if (!webdavClient) throw new Error('未连接到 WebDAV 服务器');
  const contents_res = await webdavClient.getDirectoryContents(path, { details: true });
  const contents = contents_res.data;
  // // 标准化路径（确保无结尾斜杠）
  const normalizedDirPath = path.replace(/\/$/, '').replace(/^\//, ''); // 去掉末尾的/
  const firstItem = contents[0];
  // 核心判断：filename 完全匹配当前目录路径 → 是父目录
  const isParentDir = firstItem?.filename === normalizedDirPath;
  // 如果是父目录则跳过，否则全部保留（兼容空目录或特殊情况）
  const filteredContents = isParentDir ? contents.slice(1) : contents;
  return { data: filteredContents };
});

ipcMain.handle('open-file', (event, localPath) => {
  shell.openPath(localPath); // 调用系统程序打开文件
});

// 右键菜单模板（动态生成）
ipcMain.handle('show-context-menu', (event, { x, y, selectedItem, currentPath }) => {
  const menuTemplate = currentPath.includes('个人空间') ? [
    {
      label: '新建文件夹',
      click: () => contextMenuAction(event, 'new-directory', selectedItem, currentPath)
    },
    { type: 'separator' },
    {
      label: '上传文件',
      click: () => contextMenuAction(event, 'upload-file', selectedItem, currentPath)
    },
    { type: 'separator' },
    {
      label: '刷新',
      click: () => contextMenuAction(event, 'refresh', selectedItem, currentPath)
    }
  ] : [
    {
      label: '刷新',
      click: () => contextMenuAction(event, 'refresh', selectedItem, currentPath)
    }
  ];

  if (selectedItem) {
    menuTemplate.push({ type: 'separator' });
    menuTemplate.push(
    {
      label: '重命名',
      click: () => contextMenuAction(event, 'rename', selectedItem, currentPath)
    },
    {
      label: '删除',
      click: () => contextMenuAction(event, 'delete', selectedItem, currentPath)
    });
  }

  const menu = Menu.buildFromTemplate(menuTemplate);
  menu.popup({ x, y });
});

async function contextMenuAction(event, action, selectedItem, currentPath) {
  try {
    switch (action) {
      case 'new-directory': {
        event.sender.send('create-directory', { currentPath });
        break;
      }
      
      case 'upload-file': {
        const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
          properties: ['openFile', 'multiSelections']
        });
        
        if (!canceled && filePaths.length > 0) {
          const targetPath = currentPath || '';
          for (const localPath of filePaths) {
            const fileName = path.basename(localPath);
            const remotePath = `${targetPath}/${fileName}`;
            const fileStream = fs.createReadStream(localPath);
            await webdavClient.putFileContents(remotePath, fileStream);
            const localRoot = path.join(VIRTUAL_ROOT, `${_userInfo.xm}-${_userInfo.bh}`);
            await copyFileWithCheck(remotePath, localRoot); // 复制远程文件到本地
            console.log(`已同步文件 ${remotePath} 到本地虚拟目录`);
            event.sender.send('operation-success', { action, path: remotePath });
          }
        }
        break;
      }
      case 'refresh': {
        event.sender.send('operation-success', { action });
        break;
      }
      case 'rename': {
        event.sender.send('rename', { selectedItem, currentPath });
        break;
      }
      case 'delete': {
        const { response } = await dialog.showMessageBox(mainWindow, {
          type: 'warning',
          title: '确认删除',
          message: `确定要删除 "${selectedItem.basename}" 吗?`,
          buttons: ['确定', '取消']
        });
        
        if (response === 0) {
          try {
            if (selectedItem.type === 'directory') {
              await deleteDirectoryRecursive(selectedItem.filename);
            } else {
              await webdavClient.deleteFile(selectedItem.filename);
              await deleteLocalFile(selectedItem.filename);
            }
            event.sender.send('operation-success', { action, path: selectedItem.filename });
          } catch (error) {
            console.log(error);
          }
        }
        break;
      }
    }
  } catch (error) {
    event.sender.send('operation-error', { action, error: error.message });
  }
}

async function deleteDirectoryRecursive(folderPath) {
  try {
    // 1. 获取文件夹内容
    const contents = await webdavClient.getDirectoryContents(folderPath);
    
    // 2. 递归删除所有子项（深度优先）
    for (const item of contents) {
      const itemPath = `${folderPath}/${item.basename}`;
      
      if (item.type === 'directory') {
        // 递归删除子文件夹（会先删除其所有内容）
        await deleteDirectoryRecursive(itemPath);
      } else {
        // 删除文件
        await webdavClient.deleteFile(itemPath);
      }
    }
    await webdavClient.deleteFile(`${folderPath}/`);
    await deleteLocalDirectory(folderPath);
    return true;
  } catch (error) {
    console.error('递归删除失败:', folderPath, error);
    throw error;
  }
}

// 删除本地虚拟目录中的文件
async function deleteLocalFile(remotePath) {
  try {
    const localRoot = path.join(VIRTUAL_ROOT, `${_userInfo.xm}-${_userInfo.bh}`);
    const localPath = path.join(localRoot, remotePath.replace(/^\//, ''));
    
    if (fs.existsSync(localPath)) {
      await fs.promises.unlink(localPath);
      console.log(`已删除本地文件: ${localPath}`);
    }
  } catch (error) {
    console.error('删除本地文件失败:', error);
  }
}

// 删除本地虚拟目录中的目录
async function deleteLocalDirectory(remotePath) {
  try {
    const localRoot = path.join(VIRTUAL_ROOT, `${_userInfo.xm}-${_userInfo.bh}`);
    const localPath = path.join(localRoot, remotePath.replace(/^\//, ''));
    
    if (fs.existsSync(localPath)) {
      await fs.promises.rm(localPath, { recursive: true, force: true });
      console.log(`已删除本地目录: ${localPath}`);
    }
  } catch (error) {
    console.error('删除本地目录失败:', error);
  }
}

ipcMain.handle('create-new-directory', async (event, { currentPath, basename }) => {
  const newPath = `${currentPath || ''}/${basename}`;
  await webdavClient.createDirectory(newPath);
  const localRoot = path.join(VIRTUAL_ROOT, `${_userInfo.xm}-${_userInfo.bh}`);
  await copyDirectoryWithCheck(newPath, localRoot);
  event.sender.send('operation-success', { action: 'create-new-directory', path: currentPath });
});

// 重命名
ipcMain.handle('rename', async (event, { currentPath, oldName, newName }) => {
  try {
    const newPath = `${currentPath}/${newName}`;
    await webdavClient.moveFile(oldName, newPath);
    await renameLocalItem(oldName, newPath);
    event.sender.send('operation-success', { action: 'rename' });
  } catch (error) {
    console.error(error.message);
  }
});

// 重命名本地虚拟目录中的文件或目录
async function renameLocalItem(oldRemotePath, newRemotePath) {
  try {
    const localRoot = path.join(VIRTUAL_ROOT, `${_userInfo.xm}-${_userInfo.bh}`);
    const oldLocalPath = path.join(localRoot, oldRemotePath.replace(/^\//, ''));
    const newLocalPath = path.join(localRoot, newRemotePath.replace(/^\//, ''));
    
    // 确保目标目录存在
    const newLocalDir = path.dirname(newLocalPath);
    if (!fs.existsSync(newLocalDir)) {
      await fs.promises.mkdir(newLocalDir, { recursive: true });
    }
    
    // 重命名本地文件或目录
    if (fs.existsSync(oldLocalPath)) {
      await fs.promises.rename(oldLocalPath, newLocalPath);
      console.log(`已重命名本地项: ${oldLocalPath} -> ${newLocalPath}`);
    }
  } catch (error) {
    console.error('重命名本地项失败:', error);
  }
}

ipcMain.handle('webdav-upload', async (event, localPath, remotePath) => {
  if (!webdavClient) throw new Error('未连接到 WebDAV 服务器');
  // 检查文件是否存在
  if (!fs.existsSync(localPath)) {
    throw new Error('本地文件不存在');
  }
  if (!remotePath.startsWith('/')) {
    throw new Error('无效的远程路径');
  }
  // 使用流上传（推荐大文件）
  const readStream = fs.createReadStream(localPath);
  return webdavClient.putFileContents(remotePath, readStream);
});


ipcMain.handle('dropFileToLocal', async (event, filePath) => {
  const localRoot = path.join(VIRTUAL_ROOT, `${_userInfo.xm}-${_userInfo.bh}`);
  await copyFileWithCheck(filePath, localRoot);
});

// Windows 挂载逻辑
async function mountOnWindows(username, password, serverUrl) {
  try {
    const driveLetter = 'Z:';
    
    // 检查驱动器是否已挂载
    const isMounted = await checkDriveMounted(driveLetter);
    if (isMounted) {
      console.log('驱动器已挂载，先卸载');
      await unmountDrive(driveLetter);
    }
    
    // 构造挂载命令
    const cmd = `net use ${driveLetter} "${serverUrl}" /user:"${username}" "${password}" /persistent:no`;
    
    console.log('执行命令:', cmd);
    
    return new Promise((resolve, reject) => {
      exec(cmd, (error, stdout, stderr) => {
        if (error) {
          console.error('命令执行失败:', error.message);
          console.error('标准错误输出:', stderr);
          
          // 尝试使用 WebClient 服务
          if (error.message.includes('53')) {
            console.log('尝试启用 WebClient 服务...');
            enableWebClientService()
              .then(() => resolve(true))
              .catch(err => reject(`映射失败: ${err.message}`));
          } else {
            reject(`映射失败: ${error.message}`);
          }
        } else {
          console.log('命令执行成功:', stdout);
          resolve(true);
        }
      });
    });
  } catch (error) {
    console.error('Windows 挂载失败:', error);
    throw error;
  }
}

// 检查驱动器是否已挂载（Windows）
function checkDriveMounted(driveLetter) {
  return new Promise((resolve) => {
    exec(`net use`, (error, stdout) => {
      resolve(stdout.includes(driveLetter));
    });
  });
}

// 卸载驱动器（Windows）
function unmountDrive(driveLetter) {
  const execF = `subst ${driveLetter} /D`;
  // const execF = `net use ${driveLetter} /delete`;
  return new Promise((resolve, reject) => {
    exec(`subst`, (error, stdout) => {
      const isMounted = stdout.includes(`${driveLetter}\\`);
      if (!isMounted) {
        console.log(`${driveLetter}: 未映射，无需卸载`);
        return resolve(true);
      }
      exec(execF, (error, stdout, stderr) => {
        if (error) {
          console.error('卸载失败:', error.message);
          reject(error);
        } else {
          console.log(`卸载 ${driveLetter}: 成功`);
          resolve(true);
        }
      });
    });
  });
}

// 启用 WebClient 服务（Windows）
function enableWebClientService() {
  return new Promise((resolve, reject) => {
    exec('sc config WebClient start=auto', (error) => {
      if (error) {
        console.error('启用 WebClient 服务失败:', error.message);
        reject(new Error('请确保 WebClient 服务已启用'));
      } else {
        exec('net start WebClient', (startError) => {
          if (startError) {
            console.error('启动 WebClient 服务失败:', startError.message);
            reject(new Error('请手动启动 WebClient 服务'));
          } else {
            resolve(true);
          }
        });
      }
    });
  });
}

// 系统映射功能
ipcMain.handle('webdav-map-system', async (event, { username, password, serverUrl }) => {
  try {
    const isMounted = await mountOnWindows(username, password, serverUrl);
    event.sender.send('webdav-mapped', isMounted);
    return isMounted;
  } catch (error) {
    console.error('映射过程中出错:', error);
    throw new Error(`映射失败: ${error.message}`);
  }
});

app.whenReady().then(async() => {
  await createWindow();
  app.on("activate", async function () {
    if (BrowserWindow.getAllWindows().length === 0) await createWindow();
  });
});

app.on('window-all-closed', async () => {
  // 不再直接退出，而是隐藏窗口
  if (process.platform !== 'darwin') {
    // 确保托盘存在
    if (!tray) setupTray();
  }
});

function initAutoUpdater() {
  const updateExePath = path.join(
    path.dirname(process.execPath),
    '..',
    'update.exe'
  );

  // 调用 Update.exe 检查更新（参数对应 Gitee 上的 RELEASES 地址）
  exec(
    `"${updateExePath}" --checkForUpdates "${forgeConfig.packagerConfig.publish.url}"`,
    (error, stdout, stderr) => {
      if (error) {
        console.error('更新检查失败:', error);
        return;
      }
      console.log('更新检查结果:', stdout);
    }
  );
}
ipcMain.on('restart-app', () => {
  autoUpdater.quitAndInstall();
});